package com.yksj.healthtalk.ui.doctorstation.service;

import org.universalimageloader.core.ImageLoader;

import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;


/**
 * 分组成员添加
 * @author zhao
 */
public class DoctorServiceGroupMenberAddActivity extends BaseFragmentActivity implements OnClickListener {
	
	ListView mListView;
	CheckBox mCheckBox;
	String userId;
	String PATIENT_GROUP_ID;
	JSONObject mJsonObject;
	DataListAdapter mAdapter;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_service_group_menmer_add_layout);
		userId = SmartFoxClient.getLoginUserId();
		
		String jsonStr = null;
		if(arg0 != null){
			jsonStr = arg0.getString("mJsonObject");
		}else{
			jsonStr = getIntent().getStringExtra("json");
		}
		try{
			mJsonObject = JSON.parseObject(jsonStr);
			PATIENT_GROUP_ID = mJsonObject.getString("PATIENT_GROUP_ID");
		}catch(Exception e){
			e.printStackTrace();
		}
		
		initUI();
		
		initData();
	}
	
	private void initUI(){
		initTitle();
		setBackBtn("返回",this);
		titleTextV.setText("添加成员");
		setRightBtnYellowBg("确定",this);
		mListView = (ListView)findViewById(android.R.id.list);;
		mCheckBox = (CheckBox)findViewById(R.id.check_all);
		mListView.setAdapter(mAdapter = new DataListAdapter());
		mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isCheck) {
				if(isCheck){
					mAdapter.onSelectAll();
				}else{
					mAdapter.unSelectAll();
				}
			}
		});
	}
	
	private void initData(){
		HttpRestClient.doHttpQueryGroups(userId, "5","1", String.valueOf(Integer.MAX_VALUE), "", "0", new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				JSONArray array = response.getJSONArray("dataList");
				mAdapter.onDataChange(array);
				mCheckBox.setVisibility(View.VISIBLE);
			}
		});
	}
	
	/**
	 * 添加成员
	 */
	private void onAddMenber(){
//		customerId 我的id patientGroupId 组id otherCustomerIds 需要添加的成员Id，用逗号分隔
		//移除不需要添加的
		if(mAdapter.mChooseArray.size() == 0){
			ToastUtil.showToastPanl("未选择添加成员");
			return;	
		}
		RequestParams params = new RequestParams();
		params.put("customerId", userId);
		params.put("patientGroupId", mJsonObject.getString("PATIENT_GROUP_ID"));
		StringBuffer buffer = new StringBuffer();
		for (Object obj : mAdapter.mChooseArray) {
			buffer.append(((JSONObject)obj).getString("customerId"));
			buffer.append(",");
		}
		
		if(-1!=buffer.indexOf(SmartControlClient.getControlClient().getUserId())){
			SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "您不能把自己添加进特殊收费人群");
			return;
		}
		
		params.put("otherCustomerIds",buffer.toString());
		HttpRestClient.doHttpAddPatientGroupMember(params, new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);
				if(response.containsKey("error_message")){
					ToastUtil.showShort(response.getString("error_message"));
				}else{
					ToastUtil.showShort("添加成功");
					finish();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back://
			onBackPressed();
			break;
		case R.id.title_right2://添加
			onAddMenber();
			break;
		}
	}
	
	
	
	class DataListAdapter extends BaseAdapter{
		JSONArray mArray  = new JSONArray();
		JSONArray mChooseArray = new JSONArray();
		
		private void onSelectAll(){
			mChooseArray.clear();
			mChooseArray.addAll(mArray);
			notifyDataSetChanged();
		}
		
		private void unSelectAll(){
			mChooseArray.clear();
			notifyDataSetChanged();
		}
		
		
		private void onDataChange(JSONArray array){
			this.mArray = array;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mArray.size();
		}

		@Override
		public JSONObject getItem(int arg0) {
			// TODO Auto-generated method stub
			return mArray.getJSONObject(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			final ViewHolder holder;
			final JSONObject jsonObject = getItem(arg0);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(R.layout.user_info_item_checkbox,null) ;
				holder.distance = (TextView)convertView.findViewById(R.id.distance);
				holder.head = (ImageView) convertView.findViewById(R.id.head_image);
				holder.personName = (TextView) convertView.findViewById(R.id.name);
				holder.headSex = (ImageView) convertView.findViewById(R.id.head_sex);
				holder.v = (ImageView) convertView.findViewById(R.id.v);
				holder.note = (TextView) convertView.findViewById(R.id.note);
				holder.attentionSalon = (ImageView)convertView.findViewById(R.id.is_friend);
				holder.check = (CheckBox)convertView.findViewById(R.id.check);
				convertView.setTag(holder);
				holder.headSex.setImageDrawable(getResources().getDrawable(R.drawable.sex_drawable));
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			if(!jsonObject.containsKey("display_name")){
				if(jsonObject.getString("customerNickname").length() != 0){
					String name = jsonObject.getString("customerNickname")+"("+jsonObject.getString("customerAccounts")+")";
					jsonObject.put("display_name", name);
				}else{
					jsonObject.put("display_name", jsonObject.getString("customerAccounts"));
				}
			}
			holder.note.setText(jsonObject.getString("personalNarrate"));
			holder.personName.setText(jsonObject.getString("display_name"));
			final LevelListDrawable listDrawable = (LevelListDrawable)holder.headSex.getDrawable();
			listDrawable.setLevel(jsonObject.getIntValue("customerSex"));
			holder.headSex.getDrawable();
			holder.v.setVisibility(CustomerInfoEntity.isShowDoctorV(jsonObject.getIntValue("roleId"))?View.VISIBLE:View.GONE);
			ImageLoader.getInstance().displayImage(jsonObject.getString("customerSex"),jsonObject.getString("clientIconBackground")
													, holder.head);
			holder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(isChecked){
						if(!mChooseArray.contains(jsonObject))
						{
							mChooseArray.add(jsonObject);
						}
					}else{
						mChooseArray.remove(jsonObject);
					}
				}
			});
			holder.check.setChecked(mChooseArray.contains(jsonObject));
			return convertView;
		}
	}
	
	private static  class ViewHolder {
		private TextView note;//描述
		private ImageView head; // 头像
		private TextView personName; // 名称
		private ImageView headSex; // 性别
		private ImageView v;
		private TextView message;//消息的图标
		private ImageView attentionSalon;//是否是关注的好友
		private TextView distance;
		private CheckBox check;
	}
	
	
}
